package the.one.brand.ui.fragment

import android.os.Bundle
import android.view.View
import androidx.lifecycle.rxLifeScope
import com.qmuiteam.qmui.widget.section.QMUISection
import com.qmuiteam.qmui.widget.section.QMUIStickySectionAdapter
import rxhttp.wrapper.cahce.CacheMode
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.toResponse
import the.one.base.constant.DataConstant
import the.one.base.ui.fragment.BaseSectionLayoutFragment
import the.one.base.ui.presenter.BasePresenter
import the.one.base.widge.decoration.SpacesItemDecoration
import the.one.brand.R
import the.one.brand.entity.*
import the.one.brand.net.Url
import the.one.brand.ui.adapter.SeriesAdapter
import java.util.*

class SeriesListFragment : BaseSectionLayoutFragment<SeriesSection,SeriesSection>() {

    val mDataMap = mutableMapOf<String,MutableList<Series>>()
    lateinit var mBrand: Brand

    companion object {
        fun newInstance(brand: Brand): SeriesListFragment {
            val fragment = SeriesListFragment()
            val bundle = Bundle()
            bundle.putParcelable(DataConstant.DATA, brand)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun initView(rootView: View?) {
        mBrand = requireArguments().getParcelable(DataConstant.DATA)
        setTitleWithBackBtn(mBrand.brand_name)
        super.initView(rootView)
    }

    override fun initStickyLayout() {
        super.initStickyLayout()
        val space = resources.getDimension(R.dimen.series_space).toInt()
        mSectionLayout.recyclerView.addItemDecoration(SpacesItemDecoration(1,0,space,space,0,0))
    }


    override fun requestServer() {
        rxLifeScope.launch({
            val data = RxHttp.get(Url.SERIES)
                    .add("brandid", mBrand.id)
                    .setCacheMode(CacheMode.READ_CACHE_FAILED_REQUEST_NETWORK)
                    .toResponse<List<Series>>()
                    .await()
            parseData(data)
        }, {

        })
    }

    /**
     * 解析数据
     * 把数据转成显示所需要的格式
     */
    private fun parseData(series: List<Series>?){
        if(null == series){
            showEmptyPage("空")
            return
        }
        // 按车类型排序
        Collections.sort(series, LevelComparator())
        val levels = mutableListOf<Level>()
        val sections = mutableListOf<QMUISection<SeriesSection, SeriesSection>>()
        for (s in series){
            val key = s.levelname
           if(mDataMap.containsKey(key)){
               mDataMap[key]!!.add(s)
           }else{
               levels.add(Level(s.levelid,s.levelname))
               val items = mutableListOf<Series>()
               items.add(s)
               mDataMap[key] = items
           }
        }
        mDataMap.forEach{
            sections.add(parseSections(it.key,it.value))
        }
        mAdapter.setData(sections)
        mSectionLayout.setBackgroundColor(getColor(R.color.qmui_config_color_background))
        showContentPage()
    }

    private fun parseSections(key:String, series: List<Series>):QMUISection<SeriesSection, SeriesSection>{
        val levels = mutableListOf<SeriesSection>()
        for (se in series){
            levels.add(SeriesSection(se))
        }
        val series = Series()
        series.levelname = key
        return QMUISection<SeriesSection, SeriesSection>(SeriesSection(series),levels)
    }

    /**
     * Level排序
     */
    private class LevelComparator : Comparator<Series> {
        override fun compare(lhs: Series, rhs: Series): Int {
            return if(lhs.levelid>rhs.levelid) 1 else -1
        }
    }

    override fun getPresenter(): BasePresenter<*>? {
        return null
    }

    override fun onItemClick(holder: QMUIStickySectionAdapter.ViewHolder?, position: Int) {
        val section = mAdapter.getSectionItem(position) as SeriesSection
        startFragment(ModelsFragment.newInstance(section.data))
    }

    override fun onItemLongClick(holder: QMUIStickySectionAdapter.ViewHolder?, position: Int): Boolean = true

    override fun createAdapter(): QMUIStickySectionAdapter<SeriesSection, SeriesSection, QMUIStickySectionAdapter.ViewHolder>  = SeriesAdapter()

    override fun loadMore(section: QMUISection<SeriesSection, SeriesSection>?, loadMoreBefore: Boolean) {
    }

}